package com.epoch.servicetest.service.impl;

import bean.response.ResponseBean;
import bean.response.ResultEnum;
import com.epoch.servicetest.dao.*;
import com.epoch.servicetest.service.TestService;
import com.epoch.servicetest.test.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.ResultInfoUtil;
import utils.validcode.DataValid;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * test service impl
 * @author Seven
 * @date 2021/12/1
 */
@Service
@Transactional
public class TestServiceImpl implements TestService {

    @Autowired
    private TestDao testDao;

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private QuestionItemDao questionItemDao;

    @Autowired
    private ExamTestDao examTestDao;

    @Autowired
    private StuWrongDao stuWrongDao;

    @Autowired
    private StuTestDao stuTestDao;

    @Override
    public ResponseBean getTests() {
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取试题基本内容成功",testDao.getTests());
    }

    @Override
    public ResponseBean getTestsByTypeContent(String typeContent) {
       if(DataValid.containsSqlInjection(typeContent)){
           return ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST,"含有非法字符，含有sql注入风险");
        }
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"通过试题类型获取试题基本内容成功",testDao.getTestsByTypeContent(typeContent));
    }

    /**
     * 根据主键id获取试题
     * @param id
     * @return
     */
    @Override
    public ResponseBean getTestByPrimaryId(Integer id) {

        Test test = testDao.getTestByPrimaryId(id);
        if (test == null){
            ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST,"试题id不存在");
        }
        //填写试题题目
        return ResultInfoUtil.buildSuccess(ResultEnum.OK, "获取试题成功",writeTest(test));
    }

    @Override
    public ResponseBean getExamTestById(Integer id) {
        //查找该试卷是否存在
        ExamTest examTest = examTestDao.getExamTestById(id);
        if (examTest == null){
            return ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST, "访问的试卷不存在");
        }
        //填写试卷
        //填写听力
        if (examTest.getListenId() != null && testDao.getTestByPrimaryId(examTest.getListenId()) != null){
            Test listenTest = testDao.getTestByPrimaryId(examTest.getListenId());
            examTest.setListenList(writeTest(listenTest));
        }
        //填写阅读
        if (examTest.getReadId() != null && testDao.getTestByPrimaryId(examTest.getReadId()) != null){
            Test readList = testDao.getTestByPrimaryId(examTest.getReadId());
            examTest.setReadList(writeTest(readList));
        }
        //填写写作
        if (examTest.getWritingId() != null && testDao.getTestByPrimaryId(examTest.getWritingId()) != null){
            Test writeList = testDao.getTestByPrimaryId(examTest.getWritingId());
            examTest.setWritingList(writeTest(writeList));
        }
        //填写翻译
        if (examTest.getTranslationId() != null && testDao.getTestByPrimaryId(examTest.getTranslationId()) != null){
            Test translationList = testDao.getTestByPrimaryId(examTest.getTranslationId());
            examTest.setTranslationList(writeTest(translationList));
        }
        //填写语法
        if (examTest.getGrammarId() != null && testDao.getTestByPrimaryId(examTest.getGrammarId()) != null){
            Test grammarList = testDao.getTestByPrimaryId(examTest.getGrammarId());
            examTest.setGrammarList(writeTest(grammarList));
        }
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取试卷成功",examTest);
    }

    /**
     * 填写一个test的题目 听力 语法 阅读
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Test writeTest(Test test){
        //填写试题题目
        List<Question> questions = questionDao.getQuestionByTestId(test.getId());
        if (questions == null){
            System.out.println("试题没有内容");
            ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST, "试题没有内容");
        }
        //填写题目的选项
        for (int i = 0; i < questions.size(); i++) {
            questions.get(i).setQuestionItemList(questionItemDao.getQuestionItemByQuestionId(questions.get(i).getId()));
        }
        test.setQuestionList(questions);
        return test;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addStuWrong(HashMap<String, Object> map, HttpServletRequest request) {

        Integer testIdInt = null;
        String wrongInfo= null;
        String csPhone = null;
        Consumer consumer = null;
        try{
            String testIdStr = (String) map.get("testId");
            wrongInfo = (String) map.get("wrongInfo");
            testIdInt = Integer.parseInt(testIdStr);
            //获取当前用户的基本信息
//            csPhone = Objects.requireNonNull(JwtUtil.parseJWT(request.getHeader("Authorization"))).getId();
//            consumer = consumerDao.getByCsPhone("18096278801");
        }catch (Exception e){
            System.out.println("请求数据不完整");
            return ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST,"请求数据不完整");
        }
        String[] answer = wrongInfo.split(",");
        Test test = testDao.getTestByPrimaryId(testIdInt);
        //错题题号
        Integer questionItemId;
        float all = answer.length;
        float inCorrect = 0;
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        //依次插入每个错题
        for (int i = 0; i < answer.length-1; i++) {
            if (!answer[i].startsWith("0")){
                //插入错题
                questionItemId = Integer.parseInt(answer[i].substring(1));
                String questionItemWrong = answer[i].substring(0,1);
                if (questionItemWrong.equals("1")){
                    questionItemWrong = "A";
                }else if(questionItemWrong.equals("2")){
                    questionItemWrong = "B";
                }else if (questionItemWrong.equals("3")){
                    questionItemWrong = "C";
                }else {
                    questionItemWrong = "D";
                }
                inCorrect++;
                //进行基本信息填写
                //判断此题是否已经存在
//                StuWrong stuWrongOld = stuWrongDao.getStuWrongByCsIdQuestionItemId(consumer.getId(), questionItemId);
                StuWrong stuWrongOld = stuWrongDao.getStuWrongByCsIdQuestionItemId(1, questionItemId);
                if (stuWrongOld != null){
                    if (!stuWrongOld.getWrong().contains(questionItemWrong)){
                        stuWrongOld.setWrong(stuWrongOld.getWrong()+questionItemWrong);
                    }
                    stuWrongOld.setUpdateDate(date);
                    stuWrongOld.setTime(stuWrongOld.getTime()+1);
                    //更新stuWrong
                    stuWrongDao.updateStuWrongByQuestionItemIdByCsId(stuWrongOld);
                }else {
                    QuestionItem questionItem = questionItemDao.getQuestionItemByQuestionItemId(questionItemId);
                    StuWrong stuWrong = new StuWrong();
                    stuWrong.setCsId(consumer.getId());
                    stuWrong.setTestId(testIdInt);
                    stuWrong.setQuestionItemId(questionItemId);
                    stuWrong.setWrong(questionItemWrong);
                    stuWrong.setUpdateDate(date);
                    //添加错题
                    stuWrongDao.addStuWrong(stuWrong);
                }
            }
        }
        //计算正确率
        double correctRate = (1.0 - inCorrect/all)*100.0;
        //学生做题记录基本信息填写
        StuTest stuTest = new StuTest();
        stuTest.setCsId("U"+csPhone);
        stuTest.setTestId(test.getTestId());
        stuTest.setTimes(date);
        stuTest.setCorrect(correctRate);
        stuTest.setTestPrimaryId(testIdInt);
        //插入学生做题记录
        stuTestDao.addStuTestByStuTest(stuTest);
        //修改test的正确率
        double testCorrectRate = test.getCorrectRate();
        double testDoNum =  test.getDoNum();
        testCorrectRate = (testDoNum * testCorrectRate + correctRate)/(testDoNum + 1);
        test.setCorrectRate(testCorrectRate);
        //判断难度 level
        String level = "简单";
        if (testCorrectRate < 60.0){
            level = "困难";
        }else if (testCorrectRate < 80.0){
            level = "中等";
        }else{
        }
        test.setLevel(level);
        //修改test 的level correctRate
        testDao.updateTestLevelCorrectRate(test);
        return ResultInfoUtil.buildSuccess(ResultEnum.OK, "添加做题记录及错题成功",null);
    }

    @Override
    public ResponseBean getStuWrongByCsId(Integer id) {
        List<StuWrong> stuWrongList = stuWrongDao.getStuWrongByCsId(id);
        for (int i = 0; i < stuWrongList.size(); i++) {
            //依次填写每个错题的其他信息
            QuestionItem questionItem = questionItemDao.getQuestionItemByQuestionItemId(stuWrongList.get(i).getQuestionItemId());
            //from 出处
            Question question = questionDao.getQuestionByQuestionId(questionItem.getQuestionId());
            stuWrongList.get(i).setFrom(testDao.getTestByPrimaryId(question.getTestId()).getTestName()+" "+ question.getTitle() + " 题号："+ questionItem.getId());
            //错误选项
            String wrong = stuWrongList.get(i).getWrong();
            String wrongInfo = "错误选项：";
            if (wrong.contains("A")){
                wrongInfo = wrongInfo +"A："+questionItem.getA();
            }
            if (wrong.contains("B")){
                wrongInfo = wrongInfo +"B："+questionItem.getB();
            }
            if (wrong.contains("C")){
                wrongInfo = wrongInfo +"C："+questionItem.getC();
            }
            if (wrong.contains("D")){
                wrongInfo = wrongInfo +"D："+questionItem.getD();
            }
            stuWrongList.get(i).setWrong(wrongInfo);
            //正确答案
            String correct = questionItem.getCorrect();
            if (correct.equals("A")){
                correct = correct +"："+questionItem.getA();
            }else if (correct.equals("B")){
                correct = correct +"："+questionItem.getB();
            }else if (correct.equals("C")){
                correct = correct +"："+questionItem.getC();
            }else {
                correct = correct +"："+questionItem.getD();
            }
            stuWrongList.get(i).setCorrect("正确选项："+correct);
            //解析
            stuWrongList.get(i).setAnalyze(questionItem.getAnalyze());
        }
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取学生错题成功",stuWrongList);
    }


}
